package com.suanfa;


import java.util.Arrays;

/**
 * 选择排序
 *
 * @Author weijingchen
 * @Date 2025/5/28 21:01
 * @Version 1.0.0
 */
public class Test11 {

    public static void main(String[] args) {
        int[] arr1 = {8, 10, 9, 18, 7, 16, 5, 4, 3, 2, 11};
        //selectionSort(arr1);
        insertionSort(arr1);
    }

    public static void selectionSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        int count = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                minIndex = arr[j] < arr[minIndex] ? j : minIndex;
            }
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
            count++;
        }
        System.out.println(
                "selectionSort=" + count
        );
        String methodName = new Throwable().getStackTrace()[0].getMethodName();
        System.out.println(methodName + "\t" + Arrays.toString(arr));
    }

    public static void insertionSort(int arr[]) {
        int count=0;
        for (int i = 1; i < arr.length; i++) {
            //插入的数
            int insertVal = arr[i];
            //被插入的位置(准备和前一个数比较)
            int index = i - 1;
            //如果插入的数比被插入的数小
            while (index >= 0 && insertVal < arr[index]) {
                //将把 arr[index] 向后移动
                arr[index + 1] = arr[index];
                //让 index 向前移动
                index--;
                count++;
            }
            //把插入的数放入合适位置
            arr[index + 1] = insertVal;
        }
        System.out.println(count);
        System.out.println(Arrays.toString(arr));
    }
}
